﻿using AutoMapper;
using DFGK_WMS.Context;
using DFGK_WMS.IRepository;
using DFGK_WMS.Model.DTO;
using DFGK_WMS.Model.Models;
using Microsoft.EntityFrameworkCore;
using System.Text.RegularExpressions;

namespace DFGK_WMS.Repository
{
    public class ShelvesRepository : BaseRepository<TShelf>, IShelvesRepository
    {
        public ShelvesRepository(DFGK_DB context, IMapper mapper) : base(context, mapper)
        {
        }
        /// <summary>
        /// 添加货架
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool AddShel(ShelvesDto obj, out string message)
        {
            message = "";
            try
            {
                //string code = "Shelve";
                //var aobj = Context.TShelves.AsNoTracking().Where(x => x.Code.Contains(code)).OrderByDescending(x => x.CreateDate).FirstOrDefault();
                //if (aobj != null)
                //{
                //    string pattern = @"\d+";
                //    MatchCollection matches = Regex.Matches(aobj.Code, pattern);
                //    string value = matches[matches.Count - 1].Value;
                //    int values = Convert.ToInt32(value);
                //    values++;
                //    obj.Code = code + values.ToString("D4");
                //}
                //else
                //{
                //    int i = 1;
                //    obj.Code = code + i.ToString("D4");
                //}

                var sobj = Context.TShelves.AsNoTracking().FirstOrDefault(x => x.Code == obj.Code);
                if (sobj != null)
                {
                    message = "编码已存在！";
                    return false;
                }

                TShelf shelf = new TShelf();
                shelf = Mapper.Map<TShelf>(obj);
                shelf.CreateUserId = obj.CreateUserId;
                shelf.CreateUserName = obj.CreateUserName;
                shelf.CreateDate = DateTime.Now;              
                //库房
                var wobj = Context.TWarehouses.Find(obj.WhId);
                if (wobj != null && wobj.Status == 1)
                {
                    shelf.WhName = wobj.Name;
                }
                else
                {
                    message = "库房不存在或已被禁用！";
                    return false;
                }
                //库区
                var bobj = Context.TAreas.Find(obj.AreaId);
                if (bobj != null && bobj.Status == 1)
                {
                    shelf.AreaName = bobj.Name;
                    shelf.AreaCode = bobj.Code;
                }
                else
                {
                    message = "库区不能再或已被禁用！";
                    return false;
                }

                using (var tran = Context.Database.BeginTransaction())
                {
                    try
                    {
                        Context.TShelves.Add(shelf);
                        int res = Context.SaveChanges();
                        if (res <= 0)
                        {
                            tran.Rollback();
                            message = "添加货架失败";
                            return false;
                        }

                        //根据货架生成对应的排信息
                        List<TRow> rows = CreateTrowByShel(shelf);

                        Context.TRows.AddRange(rows);
                        res = Context.SaveChanges();
                        if (res <= 0)
                        {
                            tran.Rollback();
                            message = "添加货架失败";
                            return false;
                        }

                        tran.Commit();
                        return true;
                    }
                    catch (Exception ex)
                    {
                        tran.Rollback();
                        message = "发生异常信息：" + ex.Message;
                        return false;


                    }

                }




            }
            catch (Exception)
            {

                throw;
            }
        }

        private List<TRow> CreateTrowByShel(TShelf shelf)
        {
            int shelfCount = Context.TShelf.Where(it => it.WhId == shelf.WhId).Count();
            int totalCount = Context.TRows.Where(it => it.WhId == shelf.WhId).Count();

            List<TRow> rowList = new List<TRow>();
            int? maxDepth = shelf.Depth - 1;
            if (shelfCount != 0)
            {
             
                //奇数货架
                if (shelfCount % 2 != 0)
                {

                    for (int? i = maxDepth; i >= 0; i--)
                    {
                        int currentRow = ++totalCount;
                        TRow row = new TRow()
                        {
                            ActualityDepthIndex = (int)i,
                            AreaId = shelf.AreaId,
                            RowName = $"{currentRow}排",
                            RowId = currentRow,
                            ShelfId = shelf.Id,
                            WhId = shelf.WhId,
                            RoutewayId = shelf.RoutewayId,
                            IsEnable = shelf.Status
                        };

                        rowList.Add(row);
                    }
                }
                else
                {
                    for (int i = 0; i <= maxDepth; i++)
                    {
                        int currentRow = ++totalCount;
                        TRow row = new TRow()
                        {
                            ActualityDepthIndex = i,
                            AreaId = shelf.AreaId,
                            RowName = $"{currentRow}排",
                            RowId = currentRow,
                            ShelfId = shelf.Id,
                            WhId = shelf.WhId,
                            RoutewayId = shelf.RoutewayId,
                            IsEnable = shelf.Status
                        };

                        rowList.Add(row);
                    }
                }
            }
            else
            {
                for (int? i = maxDepth; i >= 0; i--)
                {
                    int currentRow = ++totalCount;
                    TRow row = new TRow()
                    {
                        ActualityDepthIndex = (int)i,
                        AreaId = shelf.AreaId,
                        RowName = $"{currentRow}排",
                        RowId = currentRow,
                        ShelfId = shelf.Id,
                        WhId = shelf.WhId,
                        RoutewayId = shelf.RoutewayId,
                        IsEnable = shelf.Status
                    };

                    rowList.Add(row);
                }
            }




            return rowList;

        }
        /// <summary>
        /// 删除货架
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool DelShel(int uid)
        {
            try
            {
                var del = Context.TShelves.Find(uid);
                if (del != null)
                {
                    Context.TShelves.Remove(del);
                    return Context.SaveChanges() > 0;
                }
                return false;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 根据id获取货架信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public TShelf GetShelById(int id)
        {
            try
            {
                return Context.TShelves.Find(id);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 显示货架信息
        /// </summary>
        /// <param name="hcode"></param>
        /// <param name="hname"></param>
        /// <param name="kid"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TShelf> GetShelList(string hname, int kid, int pageIndex, int pageSize, out int totalCount)
        {
            try
            {
                var shelflist = Context.TShelves.AsNoTracking();
                if (!string.IsNullOrEmpty(hname))
                    shelflist = shelflist.Where(x => x.Name.Contains(hname));

                if (kid > 0)
                    shelflist = shelflist.Where(x => x.WhId == kid);

                totalCount = shelflist.Count();

                shelflist = shelflist.Skip((pageIndex - 1) * pageSize).Take(pageSize);
                return shelflist.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取巷道信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TRouteway> GetTRoutewayList()
        {
            try
            {
                return Context.TRouteways.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取库房(仓库)信息
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TWarehouse> GetTwarehouseList()
        {
            try
            {
                return Context.TWarehouses.ToList();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 修改货架信息
        /// </summary>
        /// <param name="u"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public bool UpdateShel(ShelvesDto u, out string message)
        {
            message = "";
            try
            {
                var list = Context.TShelves.AsNoTracking().FirstOrDefault(x => x.Id != u.Id && x.Code == u.Code);

                if (list != null)
                {
                    message = "编码已存在！";
                    return false;
                }
                TShelf shelf = new TShelf();
                shelf = Mapper.Map<TShelf>(u);
                u.ModifyDate = DateTime.Now;
                u.ModifyUserId = u.ModifyUserId;
                u.ModifyUserName = u.ModifyUserName;
                //库房
                var wobj = Context.TWarehouses.Find(u.WhId);
                if (wobj != null && wobj.Status == 1)
                {
                    shelf.WhName = wobj.Name;
                }
                else
                {
                    message = "库房不存在或已被禁用！";
                    return false;
                }
                //库区
                var aobj = Context.TAreas.Find(u.AreaId);
                if (aobj != null && aobj.Status == 1)
                {
                    shelf.AreaName = aobj.Name;
                    shelf.AreaCode = aobj.Code;
                }
                else
                {
                    message = "库区不存在或已被禁用！";
                    return false;
                }
                Context.TShelves.Update(shelf);
                return Context.SaveChanges() > 0;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 所属库区级联展示
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<Menuitem> GetWarehouseMenuitem()
        {
            var wlist = Context.TWarehouses.AsNoTracking().ToList();

            return wlist.Select(item => new Menuitem
            {
                label = item.Name,
                value = item.Id,
                icon = item.Code,
                children = GetAreaMenuitem(item.Id)
            }).ToList();
        }

        public List<Menuitem> GetAreaMenuitem(int wid)
        {
            var list = Context.TAreas.AsNoTracking().Where(x => x.WhId == wid);
            return list.Select(x => new Menuitem
            {
                label = x.Name,
                value = x.Id,
                icon = x.Code,
                children = null
            }).ToList();
        }

        /// <summary>
        /// 根据库区获取货架
        /// </summary>
        /// <param name="aid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TShelf> GetAreaShelf(int aid)
        {
            var shelf = Context.TShelves.Where(x => x.AreaId == aid);
            return shelf.ToList();

        }

        /// <summary>
        /// 根据库房获取库区
        /// </summary>
        /// <param name="wid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TArea> GetWarehouseAreaList(int wid)
        {
            var alist = Context.TAreas.AsNoTracking().Where(x => x.WhId == wid);
            return alist.ToList();
        }

        /// <summary>
        /// 根据库房选择巷道
        /// </summary>
        /// <param name="wid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<TRouteway> GetWareRouteway(int wid)
        {
            var wrlist = Context.TRouteways.AsNoTracking().Where(x => x.WhId == wid);

            return wrlist.ToList();
        }
    }
}
